package cn.yunyichina.provider.hquery.thread;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.hquery.dao.InspectDao;
import cn.yunyichina.provider.hquery.dao.PhysicalDao;
import cn.yunyichina.provider.hquery.entity.Inspect;
import cn.yunyichina.provider.hquery.entity.Physical;
import cn.yunyichina.provider.hquery.vo.PhysicalExamVo;
import cn.yunyichina.provider.iface.entity.base.MedicalCardVo;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.hisiface.examination.InspectListVoResponse;
import cn.yunyichina.provider.iface.entity.hisiface.physical.PhysicalExamListVoResponse;
import cn.yunyichina.utils.convert.JsonUtils;

/**
 * Created by 15-AK on 2017/09/18.
 */
public class PhysicalExamListRunnable  implements Runnable{
	
    private static final Logger logger = LoggerFactory.getLogger(PhysicalExamListRunnable.class);
    
    private List<PhysicalExamListVoResponse> physicalExamListVoResponseList;
    
    private PhysicalExamVo requestVo;
    
    private PhysicalDao physicalDao = SpringContextHandler.getBean(PhysicalDao.class);
    
    public PhysicalExamListRunnable(List<PhysicalExamListVoResponse> physicalExamListVoResponseList,PhysicalExamVo requestVo) {
        this.physicalExamListVoResponseList = physicalExamListVoResponseList;
        this.requestVo = requestVo;
    }

    @Override
    public void run() {

        logger.info("保存体检报告记录开始======physicalExamListVoResponseList ="+JsonUtils.toJsonString(physicalExamListVoResponseList));
        
        //查询绑定卡
        logger.info("【体检报告列表保存线程处理-查询绑定卡信息】, yyt.base.medicalcard.by.id.get request=" + JSONObject.toJSONString(requestVo));
        MedicalCardVo medicalCard =  BaseService.getMedicalCardByCardNo(requestVo.getHospitalCode(),requestVo.getPatCardNo(),requestVo.getPatCardType(), requestVo.getAppId(),null);
        if (medicalCard == null) {
            throw new CallException("18010","找不到绑定卡信息 card_no=" +requestVo.getPatCardNo());
        }
        logger.info("【体检报告列表保存线程处理-查询绑定卡信息】, yyt.base.medicalcard.by.id.get response=" + JSONObject.toJSONString(medicalCard));
        // 查询组织信息-----------------------------------------------start
        Map<String, String> orgParamMap = new HashMap<String, String>();
        orgParamMap.put("org_code", requestVo.getHospitalCode());
        logger.info("【体检报告列表-查询组织信息】, yyt.base.branchhospital.org.list request=" + JSON.toJSONString(orgParamMap));
        Response orgResponse = BaseService.callUnderlineFromInternal("yyt.base.branchhospital.org.list", JSON.toJSONString(orgParamMap));
        logger.info("【体检报告列表-查询组织信息】, yyt.base.branchhospital.org.list response=" + JSONObject.toJSONString(orgResponse));
        if (!"0".equals(orgResponse.getResultCode())) {
            throw new CallException("18010","找不到机构信息 by org_code=" + requestVo.getHospitalCode());
        }
        List<Org> orgList = JsonUtils.parseArray(orgResponse.getResult(), Org.class);
        if (org.springframework.util.CollectionUtils.isEmpty(orgList)) {
            throw new CallException("18010","找不到机构信息 by org_code=" + requestVo.getHospitalCode());
        }
        Org org = orgList.get(0);
        //存体检基本信息
        if (physicalExamListVoResponseList != null && physicalExamListVoResponseList.size() > 0) {
        	Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("orgCode", requestVo.getHospitalCode());
			//paramMap.put("branchHospitalCode", reportVo.getBranchHospitalCode());
			List<String> phyExamIds = new ArrayList<String>();
			for (PhysicalExamListVoResponse physicalExam: physicalExamListVoResponseList) {
				phyExamIds.add(physicalExam.getPhyExamId());
			}
			paramMap.put("phyExamIds", phyExamIds);
			List<String> existsPhyExamIdsIds = physicalDao.findByOrgCodeAndPhyExamIds(paramMap);
			
			// 需要插入的列表
			Physical physical = null;
	        for (PhysicalExamListVoResponse vo : physicalExamListVoResponseList) {
	        	//数据库不存在检查记录就将记录存进数据库
	        	if (!existsPhyExamIdsIds.contains(vo.getPhyExamId())) {
	        		physical = new Physical();
	        		physical.setId(PKGenerator.generateId());
	        		physical.setOrgId(org.getId());
	        		physical.setOrgName(org.getOrgName());
	        		physical.setOrgCode(requestVo.getHospitalCode());
	        		physical.setBranchId("");
	        		physical.setBranchName("");
	        		physical.setBranchCode("");
	        		physical.setPatId(medicalCard.getPatId());
	        		physical.setPatName(medicalCard.getPatName());
	        		physical.setPatSex(medicalCard.getPatSex());
	        		physical.setPatAge(medicalCard.getPatAge());
	        		physical.setPatMobile(medicalCard.getPatMobile());
	        		physical.setPatAddress(medicalCard.getPatAddress());
	        		physical.setIdCardType(medicalCard.getIdCardType());
	        		physical.setIdCardNo(medicalCard.getIdCardNo());
	        		physical.setMedicalCardNo(medicalCard.getMedicalCardNo());
	        		physical.setMedicalCardType(medicalCard.getMedicalCardType());
	        		physical.setAdmissionNo(medicalCard.getAdmissionNo());
	        		physical.setPhyExamId(vo.getPhyExamId());
	        		physical.setPhyExamName(vo.getPhyExamName());
	        		physical.setPhyExamTime("".equals(vo.getPhyExamTime())?null:vo.getPhyExamTime());
	        		//physical.setFileAddress(vo.getFileAddress());
	        		physical.setCreatedTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	        		
	        		//插入检查列表信息
	        		logger.info("要新增的报告列表=="+JsonUtils.toJsonString(physical));
	        		physicalDao.insert(physical); 
	        	}
	        }
        }
    }
}
